<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <title>问卷答题</title>
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f4f7fa;
            font-size: 0.9rem;
        }

        .card {
            background-color: #ffffff;
            border-radius: 0.75rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            padding: 1.2rem;
            margin-bottom: 1.2rem;
            transition: transform 0.2s ease-in-out;
        }

        .card:hover {
            transform: scale(1.02);
        }

        .question-title {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0.75rem;
        }

        .option-label {
            display: flex;
            align-items: center;
            margin-bottom: 0.3rem;
            cursor: pointer;
            /* 调整排列方向，让单选框在最右边 */
            flex-direction: row-reverse;
            justify-content: flex-end;
        }

        .option-label input[type="radio"] {
            margin-left: 0.5rem;
            margin-right: 0;
        }

        .submit-button {
            background-color: #3b82f6;
            color: #ffffff;
            padding: 0.6rem 1.2rem;
            border-radius: 0.5rem;
            font-weight: 600;
            transition: background-color 0.2s ease-in-out;
        }

        .submit-button:hover {
            background-color: #2563eb;
        }

        .phone-input {
            font-size: 0.9rem;
            padding: 0.4rem 0.8rem;
        }
    </style>
</head>

<body class="bg-gray-100">
<div class="container mx-auto p-4">
    <h1 class="text-2xl font-bold mb-6 text-center text-gray-800">问卷答题</h1>
    <form id="questionnaireForm">
        <div id="questionsContainer"></div>
        <!-- 手机号输入保持原样 -->
        <label for="phone" class="block text-sm font-medium text-gray-700">手机号</label>
        <input type="tel" id="phone" name="phone"
               class="mt-1 block w-full phone-input border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500">
        <button type="submit" class="mt-6 submit-button w-full">提交问卷</button>
    </form>
</div>

<script>
    const questionsContainer = document.getElementById('questionsContainer');
    const questionnaireForm = document.getElementById('questionnaireForm');

    // 修改后的模拟数据格式
    const mockQuestions = [
        {
            title: "下列哪个关键字用于表示一个类不能被继承？",
            xx1: "A) final",
            xx2: "B) abstract",
            xx3: "C) static",
            xx4: "D) private"
        },
        {
            title: "下面哪个关键字用于实现接口？",
            xx1: "A) extends",
            xx2: "B) implements",
            xx3: "C) interface",
            xx4: "D) abstract"
        },
        // 添加更多题目...
    ];

    async function fetchQuestions() {
      const url = new URL(window.location.href);
      let id= url.searchParams.get('id')? url.searchParams.get('id'):100;
        try {
            const response = await fetch('http://127.0.0.1:9999/system/questionnaire/find?id='+id);
            if (!response.ok) {
                throw new Error('网络请求失败');
            }
            const questions = await response.json();
            console.log(questions)
            renderQuestions(questions.questionlist);
        } catch (error) {
            console.error('获取题目时出错:', error);
            renderQuestions(mockQuestions);
        }
    }

    function renderQuestions(questions) {
        questionsContainer.innerHTML = ''; // 清空容器
        questions.forEach((question, index) => {
            const questionDiv = document.createElement('div');
            questionDiv.classList.add('card');

            // 题目标题
            const questionTitle = document.createElement('p');
            questionTitle.classList.add('question-title');
            questionTitle.textContent = `${index + 1}. ${question.title}`;
            questionDiv.appendChild(questionTitle);

            // 生成选项
            for (let i = 1; i <= 4; i++) {
                const optionKey = `xx${i}`;
                const optionText = question[optionKey];

                const optionInput = document.createElement('input');
                optionInput.type = 'radio';
                optionInput.required = true;
                optionInput.name = `q${index}`; // 按题目索引分组
                optionInput.value = optionText[0]; // 取A/B/C/D

                const optionLabel = document.createElement('label');
                optionLabel.classList.add('option-label');
                optionLabel.textContent = optionText;

                optionLabel.appendChild(optionInput);
                questionDiv.appendChild(optionLabel);
            }

            questionsContainer.appendChild(questionDiv);
        });
    }

    questionnaireForm.addEventListener('submit', async (event) => {
        event.preventDefault();

        // 验证所有题目是否已回答
        const allAnswered = Array.from(document.querySelectorAll('[type="radio"]'))
            .reduce((acc, radio) => {
                const groupName = radio.name;
                if (!acc[groupName]) {
                    acc[groupName] = radio.checked;
                }
                return acc;
            }, {});

        if (Object.values(allAnswered).some(answered => !answered)) {
            alert('请回答所有题目后再提交！');
            return;
        }

        // 收集答案数组
        const answers = [];
        const radioGroups = document.querySelectorAll('[type="radio"]:checked');
        radioGroups.forEach(radio => {
            answers.push(radio.value.toUpperCase()); // 确保大写字母
        });

        // 构建提交数据
        const submissionData = {
            phone: document.getElementById('phone').value,
            answers: answers.slice(0, 10) // 确保只取前10个答案
        };

        console.log('提交数据:', submissionData);
        let sumbit = {qId: 100,
            question0Answer: submissionData.phone,
            question1Answer:submissionData.answers[0],
            question2Answer:submissionData.answers[1],
            question3Answer:submissionData.answers[2],
            question4Answer:submissionData.answers[3],
            question5Answer:submissionData.answers[4],
            question6Answer:submissionData.answers[5],
            question7Answer:submissionData.answers[6],
            question8Answer:submissionData.answers[7],
            question9Answer:submissionData.answers[8],
            question10Answer:submissionData.answers[9],
        }
        try {
            const response = await fetch('http://127.0.0.1:9999/system/answer', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(sumbit)
            });

            if (!response.ok) {
                throw new Error('提交问卷失败');
            }
            console.log(response)
            alert('问卷提交成功！');
            questionnaireForm.reset();
        } catch (error) {
            console.error('提交失败:', error);
            alert('提交失败，请稍后重试');
        }
    });

    fetchQuestions();
</script>
</body>
</html>
